package com.itheima.prize.commons.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.prize.commons.config.RedisKeys;
import com.itheima.prize.commons.db.entity.CardUser;
import com.itheima.prize.commons.db.entity.ViewCardUserHit;
import com.itheima.prize.commons.db.mapper.ViewCardUserHitMapper;
import com.itheima.prize.commons.db.service.CardUserService;
import com.itheima.prize.commons.db.mapper.CardUserMapper;
import com.itheima.prize.commons.utils.ApiResult;
import com.itheima.prize.commons.utils.PageBean;
import com.itheima.prize.commons.utils.PasswordUtil;
import com.itheima.prize.commons.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author shawn
* @description 针对表【card_user(会员信息表)】的数据库操作Service实现
* @createDate 2023-12-26 11:58:48
*/
@Service
public class CardUserServiceImpl extends ServiceImpl<CardUserMapper, CardUser>
    implements CardUserService{
    @Autowired
    private RedisUtil redisUtil=new RedisUtil();
    @Autowired
    private ViewCardUserHitMapper viewCardUserHitMapper;

    @Override
    public ApiResult<CardUser> checkLogin(String account, String password) {
        //一定时间内失败次数超过5次就冻结
        Integer errorTimes = (Integer) redisUtil.get(RedisKeys.USERLOGINTIMES + account);
        long expire = redisUtil.getExpire(RedisKeys.USERLOGINTIMES + account);
        if(errorTimes!=null&&errorTimes>=5){
            return new ApiResult(0,"密码错误5次，请"+(expire/60+1)+"分钟后再登录",null);
        }
        CardUser cardUser = lambdaQuery().eq(CardUser::getUname, account).one();
        if(cardUser==null){//用户名为空
            return new ApiResult(0,"账户名或密码错误",null);
        }else{
            if(!PasswordUtil.encodePassword(password).equals(cardUser.getPasswd())){//密码不匹配
                //失败次数增加1，并且设置冻结时间为5分钟，每次加一刷新时间
                redisUtil.incr(RedisKeys.USERLOGINTIMES+account,1);
                redisUtil.expire(RedisKeys.USERLOGINTIMES+account,300);
                return new ApiResult(0,"账户名或密码错误",null);
            }
        }
        //脱敏
        cardUser.setPasswd(null);
        cardUser.setIdcard(null);
        ApiResult<CardUser> result = new ApiResult<>(1, "登录成功", cardUser);
        result.setNow(new Date());
        return result;
    }


}




